<template>
    <view class="tabs">
		<uni-search-bar @confirm="search" placeholder="库存编码" v-model="searchValue">
		</uni-search-bar>
        <scroll-view id="tab-bar" class="scroll-h" :scroll-x="true" :show-scrollbar="false" :scroll-into-view="scrollInto">
            <view v-for="(tab,index) in tabBars" :key="tab.id" class="uni-tab-item" :id="tab.id" :data-current="index" @click="ontabtap">
                <text class="uni-tab-item-title" :class="tabIndex==index ? 'uni-tab-item-title-active' : ''">{{tab.name}}</text>
            </view>
        </scroll-view>
        <view class="line-h"></view>
        <swiper :current="tabIndex" class="swiper-box" style="flex: 1; height: 100%;" :duration="300" @change="ontabchange">
            <swiper-item class="swiper-item" v-for="(tab,index1) in newsList" :key="index1">
	
				<!-- #ifndef APP-NVUE -->
				<scroll-view class="scroll-v list" style="height: 100%;" enableBackToTop="true" scroll-y @scrolltolower="loadMore(index1)">
					<uni-card v-for="(item,index2) in tab.data" :key="item.id" :title="item.product.product_name + ' 编码【'+ item.code+'】'" :sub-title="(item.shop ? item.shop.shop_name : '') " :extra="item.status_str">
						操作日志
						<view v-for="(item2, index2) in item.logs">
							<view class="">
								{{item2.user.name}} - {{item2.option_str}} - {{item2.shop.shop_name}}  [{{item2.create_time}}]
							</view>
						</view>
					</uni-card>
					<uni-load-more iconType="auto" :status="tab.status" />
				</scroll-view>
				<!-- #endif -->
            </swiper-item>
        </swiper>
    </view>
</template>
<script>

    // 缓存每页最多
    const MAX_CACHE_DATA = 100;
    // 缓存页签数量
    const MAX_CACHE_PAGE = 3;


	import api from "@/utils/api.js";

    export default {
        components: {
        },
        data() {
            return {
                newsList: [],
                cacheTab: [],
                tabIndex: 0,
                tabBars: [{
                    name: '全部',
                    id: 'all',
					request: 0,
					page: 1,
                }, {
                    name: '在店',
                    id: 'in_shop',
					request: 0,
					page: 1,
                },{
                    name: '已出库',
                    id: 'out_shop',
					request: 0,
					page: 1,
                }, {
                    name: '已售出',
                    id: 'seal',
					request: 0,
					page: 1,
                }],
                scrollInto: "",
                showTips: false,
                navigateFlag: false,
                pulling: false,
				searchValue: "",
                refreshIcon: ""
            }
        },
        onLoad() {
            setTimeout(()=>{
              this.tabBars.forEach((tabBar) => {
                  this.newsList.push({
                      data: [],
                      isLoading: false,
                      refreshText: "",
                      loadingText: '加载更多...'
                  });
              });
              this.getList(0);
            },350)
        },
		onShow() {
			this.tabBars[this.tabIndex].page = 1;
			this.newsList[this.tabIndex].data = [];
			this.getList(this.tabIndex)
		},
        methods: {
            goDetail(e) {
                if (this.navigateFlag) {
                    return;
                }
                this.navigateFlag = true;
                uni.navigateTo({
                    url: './detail/detail?title=' + e.title
                });
                setTimeout(() => {
                    this.navigateFlag = false;
                }, 200)
            },
			
			search(){
				this.tabBars[this.tabIndex].page = 1;
				this.newsList[this.tabIndex].data = [];
				this.getList(this.tabIndex)
			},
			
			
			async getList(index){
				if(this.tabBars[index].request) return false;
				this.tabBars[index].request = 1;
				let activeTab = this.newsList[index];
				activeTab.status = 'loading'
				let { result } = await api.productStockList({
					status: index,
					page: this.tabBars[index].page,
					keyword: this.searchValue
				});
				
				
				if(this.tabBars[index].page == result['data']['page']['pages']){
					activeTab.status = 'noMore'
				}else{
					activeTab.status = 'more'
				}
				
				
				if(result['data']['list']){
					this.tabBars[index].page++;
				}
				
				activeTab.data = activeTab.data.concat(result['data']['list']);
				
				this.tabBars[index].request = 0;
			},
            loadMore(e) {
                this.getList(this.tabIndex);
            },
            ontabtap(e) {
                let index = e.target.dataset.current || e.currentTarget.dataset.current;
                this.switchTab(index);
            },
            ontabchange(e) {
                let index = e.target.current || e.detail.current;
                this.switchTab(index);
            },
            switchTab(index) {
                if (this.newsList[index].data.length === 0) {
                    this.getList(index);
                }
                if (this.tabIndex === index) {
                    return;
                }
                // 缓存 tabId
                if (this.newsList[this.tabIndex].data.length > MAX_CACHE_DATA) {
                    let isExist = this.cacheTab.indexOf(this.tabIndex);
                    if (isExist < 0) {
                        this.cacheTab.push(this.tabIndex);
                        //console.log("cache index:: " + this.tabIndex);
                    }
                }

                this.tabIndex = index;
                this.scrollInto = this.tabBars[index].id;

                // 释放 tabId
                if (this.cacheTab.length > MAX_CACHE_PAGE) {
                    let cacheIndex = this.cacheTab[0];
                    this.clearTabData(cacheIndex);
                    this.cacheTab.splice(0, 1);
                    //console.log("remove cache index:: " + cacheIndex);
                }
            },
            clearTabData(e) {
                this.newsList[e].data.length = 0;
                this.newsList[e].loadingText = "加载更多...";
            },
            refreshData() {},
            onrefresh(e) {
                var tab = this.newsList[this.tabIndex];
                if (!tab.refreshFlag) {
                    return;
                }
                tab.refreshing = true;
                tab.refreshText = "正在刷新...";

                setTimeout(() => {
                    this.refreshData();
                    this.pulling = true;
                    tab.refreshing = false;
					tab.refreshFlag = false;
                    tab.refreshText = "已刷新";
                    setTimeout(() => { // TODO fix ios和Android 动画时间相反问题
                        this.pulling = false;
                    }, 500);
                }, 2000);
            },
			addShop(option_type){
				uni.navigateTo({
					url: "/pages/kucun/product_stock/add?option_type=" + option_type
				})
			},
            onpullingdown(e) {
                var tab = this.newsList[this.tabIndex];
                if (tab.refreshing || this.pulling) {
                    return;
                }
                if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
                    tab.refreshFlag = true;
                    tab.refreshText = "释放立即刷新";
                } else {
                    tab.refreshFlag = false;
                    tab.refreshText = "下拉可以刷新";
                }
            },
            newGuid() {
                let s4 = function() {
                    return (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
                }
                return (s4() + s4() + "-" + s4() + "-4" + s4().substr(0, 3) + "-" + s4() + "-" + s4() + s4() + s4()).toUpperCase();
            }
        }
    }
</script>

<style>
    /* #ifndef APP-PLUS */
    page {
        width: 100%;
        min-height: 100%;
        display: flex;
    }

    /* #endif */

    .tabs {
        flex: 1;
        flex-direction: column;
        overflow: hidden;
        background-color: #ffffff;
        /* #ifndef APP-PLUS */
        height: 100vh;
        /* #endif */
    }

    .scroll-h {
        width: 750rpx;
		/* #ifdef H5 */
		width:100%;
		/* #endif */
		height: 80rpx;
        flex-direction: row;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
        /* flex-wrap: nowrap; */
        /* border-color: #cccccc;
		border-bottom-style: solid;
		border-bottom-width: 1px; */
    }
	
	.option-button{
		margin-right: 10rpx;
	}


    .line-h {
        height: 1rpx;
        background-color: #cccccc;
    }

    .uni-tab-item {
        /* #ifndef APP-PLUS */
        display: inline-block;
        /* #endif */
        flex-wrap: nowrap;
        padding-left: 34rpx;
        padding-right: 34rpx;
    }

    .uni-tab-item-title {
        color: #555;
        font-size: 30rpx;
        height: 80rpx;
        line-height: 80rpx;
        flex-wrap: nowrap;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
    }

    .uni-tab-item-title-active {
        color: #007AFF;
    }

    .swiper-box {
        flex: 1;
    }

    .swiper-item {
        flex: 1;
        flex-direction: row;
    }

    .scroll-v {
        flex: 1;
        /* #ifndef MP-ALIPAY */
        flex-direction: column;
        /* #endif */
        width: 750rpx;
		width:100%;
    }

    .update-tips {
        position: absolute;
        left: 0;
        top: 41px;
        right: 0;
        padding-top: 5px;
        padding-bottom: 5px;
        background-color: #FDDD9B;
        align-items: center;
        justify-content: center;
        text-align: center;
    }

    .update-tips-text {
        font-size: 14px;
        color: #ffffff;
    }

    .refresh {
        width: 750rpx;
		width:100%;
        height: 64px;
        justify-content: center;
    }

    .refresh-view {
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: center;
    }

	.refresh-icon {
		width: 30px;
		height: 30px;
		transition-duration: .5s;
		transition-property: transform;
		transform: rotate(0deg);
		transform-origin: 15px 15px;
	}

	.refresh-icon-active {
		transform: rotate(180deg);
	}

	.loading-icon {
		width: 20px;
		height: 20px;
		margin-right: 5px;
		color: #999999;
	}

    .loading-text {
        margin-left: 2px;
        font-size: 16px;
        color: #999999;
    }

    .loading-more {
        align-items: center;
        justify-content: center;
        padding-top: 10px;
        padding-bottom: 10px;
        text-align: center;
    }

    .loading-more-text {
        font-size: 28rpx;
        color: #999;
    }
</style>
